<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { NDrawer, NForm, NFormItem, NInput, NSelect, NInputNumber, NColorPicker, NSwitch, NButton, NSpace, useMessage } from 'naive-ui';
import { fetchTagDetail, addTag, updateTag, fetchTagTree, type DataTag } from '@/service/api/dataplatform/tag';

const emit = defineEmits<{
  success: [];
}>();

const message = useMessage();

const visible = ref(false);
const loading = ref(false);
const operateType = ref<'add' | 'edit'>('add');
const parentId = ref<number | undefined>();

const formRef = ref();
const formModel = reactive<DataTag>({
  tagName: '',
  tagCode: '',
  parentId: 0,
  tagType: 'BUSINESS',
  description: '',
  color: '#1890ff',
  icon: '',
  sortOrder: 0,
  autoTagRule: '',
  status: 1,
  projectId: undefined,
  remark: ''
});

const tagTypeOptions = [
  { label: '业务标签', value: 'BUSINESS' },
  { label: '技术标签', value: 'TECHNICAL' },
  { label: '质量标签', value: 'QUALITY' }
];

const parentTagOptions = ref<{ label: string; value: number }[]>([]);

const rules = {
  tagName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
  tagCode: [{ required: true, message: '请输入标签编码', trigger: 'blur' }],
  tagType: [{ required: true, message: '请选择标签类型', trigger: 'change' }]
};

const title = computed(() => (operateType.value === 'add' ? '新增标签' : '编辑标签'));

/**
 * 打开抽屉
 */
async function open(type: 'add' | 'edit', id?: number, parent?: number) {
  operateType.value = type;
  parentId.value = parent;
  visible.value = true;

  // 加载父标签选项
  await loadParentTags();

  if (type === 'edit' && id) {
    await loadDetail(id);
  } else {
    resetForm();
    if (parent) {
      formModel.parentId = parent;
    }
  }
}

/**
 * 加载父标签选项
 */
async function loadParentTags() {
  try {
    const { data } = await fetchTagTree();
    parentTagOptions.value = flattenTags(data || []);
  } catch (error) {
    console.error('加载父标签失败', error);
  }
}

/**
 * 扁平化标签树
 */
function flattenTags(tags: DataTag[], level = 0): { label: string; value: number }[] {
  const result: { label: string; value: number }[] = [];
  for (const tag of tags) {
    result.push({
      label: '　'.repeat(level) + tag.tagName,
      value: tag.id!
    });
    if (tag.children && tag.children.length > 0) {
      result.push(...flattenTags(tag.children, level + 1));
    }
  }
  return result;
}

/**
 * 加载详情
 */
async function loadDetail(id: number) {
  loading.value = true;
  try {
    const { data } = await fetchTagDetail(id);
    Object.assign(formModel, data);
  } catch (error) {
    message.error('加载标签详情失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 重置表单
 */
function resetForm() {
  formModel.id = undefined;
  formModel.tagName = '';
  formModel.tagCode = '';
  formModel.parentId = 0;
  formModel.tagType = 'BUSINESS';
  formModel.description = '';
  formModel.color = '#1890ff';
  formModel.icon = '';
  formModel.sortOrder = 0;
  formModel.autoTagRule = '';
  formModel.status = 1;
  formModel.projectId = undefined;
  formModel.remark = '';
}

/**
 * 提交
 */
async function handleSubmit() {
  await formRef.value?.validate();
  loading.value = true;
  try {
    if (operateType.value === 'add') {
      await addTag(formModel);
      message.success('新增成功');
    } else {
      await updateTag(formModel);
      message.success('更新成功');
    }
    visible.value = false;
    emit('success');
  } catch (error) {
    message.error(operateType.value === 'add' ? '新增失败' : '更新失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 关闭
 */
function handleClose() {
  visible.value = false;
}

defineExpose({
  open
});

</script>

<template>
  <NDrawer v-model:show="visible" :width="600" :title="title">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-placement="left"
        :label-width="100"
      >
        <NFormItem label="标签名称" path="tagName">
          <NInput v-model:value="formModel.tagName" placeholder="请输入标签名称" />
        </NFormItem>

        <NFormItem label="标签编码" path="tagCode">
          <NInput v-model:value="formModel.tagCode" placeholder="请输入标签编码" />
        </NFormItem>

        <NFormItem label="父标签" path="parentId">
          <NSelect
            v-model:value="formModel.parentId"
            :options="[{ label: '无', value: 0 }, ...parentTagOptions]"
            placeholder="请选择父标签"
          />
        </NFormItem>

        <NFormItem label="标签类型" path="tagType">
          <NSelect
            v-model:value="formModel.tagType"
            :options="tagTypeOptions"
            placeholder="请选择标签类型"
          />
        </NFormItem>

        <NFormItem label="标签颜色" path="color">
          <NColorPicker v-model:value="formModel.color" />
        </NFormItem>

        <NFormItem label="标签图标" path="icon">
          <NInput v-model:value="formModel.icon" placeholder="请输入图标名称" />
        </NFormItem>

        <NFormItem label="排序顺序" path="sortOrder">
          <NInputNumber v-model:value="formModel.sortOrder" :min="0" style="width: 100%" />
        </NFormItem>

        <NFormItem label="自动标签规则" path="autoTagRule">
          <NInput
            v-model:value="formModel.autoTagRule"
            type="textarea"
            :rows="3"
            placeholder="请输入自动标签规则（JSON格式）"
          />
        </NFormItem>

        <NFormItem label="标签描述" path="description">
          <NInput
            v-model:value="formModel.description"
            type="textarea"
            :rows="3"
            placeholder="请输入标签描述"
          />
        </NFormItem>

        <NFormItem label="状态" path="status">
          <NSwitch v-model:value="formModel.status" :checked-value="1" :unchecked-value="0">
            <template #checked>启用</template>
            <template #unchecked>禁用</template>
          </NSwitch>
        </NFormItem>

        <NFormItem label="备注" path="remark">
          <NInput
            v-model:value="formModel.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </NFormItem>
      </NForm>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="handleClose">取消</NButton>
          <NButton type="primary" :loading="loading" @click="handleSubmit">确定</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>
